package com.deer.wms.inventory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deer.wms.base.system.model.Item.ItemInfo;
import com.deer.wms.base.system.service.ItemInfoService;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.dao.StockTakeMasterMapper;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.stockTake.*;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.inventory.service.StockTakeMasterService;
import com.deer.wms.inventory.service.StockTakeTaskService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.service.SuperServiceImpl;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.system.manage.service.ValidatorService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import static com.deer.wms.project.root.util.DateUtils.getNowDateTimeString;
import static com.deer.wms.project.root.util.FunctionUtil.nvl;

/**
 * Created by 郭靖勋 on 2020/02/06.
 */
@Service
@Transactional
public class StockTakeMasterServiceImpl extends SuperServiceImpl<StockTakeMasterMapper,StockTakeMaster> implements StockTakeMasterService {

    @Autowired
    private StockTakeMasterMapper stockTakeMasterMapper;

    @Autowired
    private ValidatorService validatorService;

    @Autowired
    private StockTakeMasterService stockTakeMasterService;

    @Autowired
    private StockTakeTaskService stockTakeTaskService;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private ItemInfoService itemInfoService;

    @Autowired
    private CaseMasterService caseMasterService;

    @Override
    public List<StockTakeMaster> findList(StockTakeMasterCriteria criteria) {
        return stockTakeMasterMapper.findList(criteria);
    }

    /**
     * 新建盘点任务，并生成盘点下架任务
     * @param stockTakeData
     * @param currentUser
     */
    @Override
    public void createStockTakeMaster(StockTakeData stockTakeData, CurrentUser currentUser) {
        StockTakeMaster stockTakeMaster = stockTakeData.getStockTakeMaster();
        String tableName = "stock_take_master";
        Integer nextId = validatorService.getNextId(tableName);

        String billNo = "PD"+"-"+nextId;
        stockTakeMaster.setBillNo(billNo);
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();
        stockTakeMaster.setCreateUserId(createUserId);
        stockTakeMaster.setCreateUserName(createUserName);
        stockTakeMaster.setCreateTime(createTime);
        stockTakeMaster.setOrganizationId(currentUser.getOrganizationId());
        save(stockTakeMaster);//保存盘点任务

        //根据盘点任务生成下架任务
//        List<StockTakeTask> taskList;
        List<Map<String,Object>> cellList;
        if (stockTakeMaster.getType()==1){//随机抽盘
            cellList = stockTakeMasterMapper.selectCell(stockTakeMaster.getWareId(),stockTakeMaster.getRandomNum());
            saveTakeTask(cellList,billNo,stockTakeMaster.getStockTakeMasterId());
        }else if (stockTakeMaster.getType()==2){//指定货位盘点
//            指定货位盘点
            String cellCodes = stockTakeMaster.getCellCodes();
            if (cellCodes.length()>0){
                String[] cellCodeList = cellCodes.split(",");
                cellList = stockTakeMasterMapper.selectByCode(stockTakeMaster.getWareId(),cellCodeList);
                saveTakeTask(cellList,billNo,stockTakeMaster.getStockTakeMasterId());
            }
        }else {//全盘
            cellList = stockTakeMasterMapper.selectAllCode(stockTakeMaster.getWareId());
            saveTakeTask(cellList,billNo,stockTakeMaster.getStockTakeMasterId());
        }

    }

    private void saveTakeTask(List<Map<String,Object>> cellList,String billNo,Integer stockTakeMasterId){
        System.out.println("cellList------------:"+cellList);
        if (cellList.size()>0){
            int i = 1;
            for (Map<String,Object> cell : cellList){
                StockTakeTask task = new StockTakeTask();
                task.setTaskBillNo(billNo +"-"+ i);
                i++;
                task.setStockTakeMasterId(stockTakeMasterId);
                task.setBoxCode(String.valueOf(cell.get("boxCode")));
                task.setCellCode(String.valueOf(cell.get("cellCode")));
                Integer inventoryId = (Integer) cell.get("inventoryId");
                task.setInventoryId(inventoryId);
                task.setCreateTime(getNowDateTimeString());
                task.setType(11);
                task.setState(1);
                stockTakeTaskService.save(task);
            }
        }else {
            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"数据错误");
        }
    }

    //stock_take_task
    //生成盘点下架任务  
//    private List<StockTakeTask> saveTakeTask(List<Map<String,Object>> cellList,String billNo,Integer stockTakeMasterId){
//        List<StockTakeTask> taskList = new ArrayList<>();
//        System.out.println("cellList------------:"+cellList);
//        if (cellList.size()>0){
//            int i = 1;
//            for (Map<String,Object> cell : cellList){
//                StockTakeTask task = new StockTakeTask();
//                task.setTaskBillNo(billNo +"-"+ i);
//                i++;
//                task.setStockTakeMasterId(stockTakeMasterId);
//                task.setCellCode(String.valueOf(cell.get("cellCode")));
//                task.setBoxCode(String.valueOf(cell.get("boxCode")));
//                task.setCreateTime(getNowDateTimeString());
//                //taskList.add(task);
//                stockTakeTaskService.save(task);
//            }
//            return taskList;
//        }else {
//            throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR,"数据错误");
//        }
//    }

    
//    @Override
//    public void createStockTakeMaster(StockTakeData stockTakeData, CurrentUser currentUser) {
//        /**
//         *  新建盘点单据
//         */
//        //      状态    2-等待审核(初始化)  1-审核通过  0-审核中  -1-审核退回
//        Integer caseState = 2;
//
//        StockTakeMaster stockTakeMaster = stockTakeData.getStockTakeMaster();
//        String tableName = "stock_take_master";
//        Integer nextId = validatorService.getNextId(tableName);
//
//        String billNo = "PD"+"-"+nextId;
//        Integer createUserId = currentUser.getUserId();
//        String createUserName = currentUser.getUserName();
//        String createTime = DateUtils.getNowDateTimeString();
//
//        caseState = caseMasterService.createCase(billNo, 5, currentUser.getUserId(), stockTakeMaster.getWareId(),stockTakeMaster.getOrganizationId());
//
//        if (StringUtils.isNotBlank(stockTakeMaster.getItemCode())) {
//            ItemInfo itemInfo = itemInfoService.findByCode(stockTakeMaster.getItemCode()).get(0);
//            if (itemInfo != null) {
//                stockTakeMaster.setItemName(itemInfo.getItemName());
//            }
//        }
//        stockTakeMaster.setCreateUserId(createUserId);
//        stockTakeMaster.setCreateUserName(createUserName);
//        stockTakeMaster.setBillNo(billNo);
//        stockTakeMaster.setCaseState(caseState);
//        stockTakeMasterService.save(stockTakeMaster);
//        if(caseState ==1){
//            saveStockTakeTasks(stockTakeMaster, billNo, createUserId, createUserName, createTime);
//        }
//    }
//
    @Override
    public void saveStockTakeTasks(StockTakeMaster stockTakeMaster, String billNo, Integer createUserId, String createUserName, String createTime) {
        // 审核后生成盘点任务
        List<Inventory> list = inventoryService.getInventoryByFromInfo(stockTakeMaster);

        for(int i=0;i<list.size();i++){
            StockTakeTask stockTakeTask = new StockTakeTask();
            stockTakeTask.setStockTakeMasterId(stockTakeMaster.getStockTakeMasterId());
            stockTakeTask.setCreateTime(createTime);
            stockTakeTask.setTaskUserId(createUserId);
            stockTakeTask.setTaskUserName(createUserName);
            stockTakeTask.setTaskBillNo(billNo);
            stockTakeTask.setInventoryId(list.get(i).getInventoryId());
//                stockTakeTask.setTaskQuantity(list.get(i).getQuantity());
            stockTakeTask.setType(11);
            stockTakeTask.setState(1);
            stockTakeTaskService.save(stockTakeTask);
        }
    }

    @Override
    public void updateStockTakeMasterState(Integer stockTakeMasterId){
        List<StockTakeTaskDto> stockTakeTaskDtos = stockTakeTaskService.findList(new StockTakeTaskCriteria(stockTakeMasterId));
        int check = 0;
        int quantity = 0;
        if(stockTakeTaskDtos.size()>0){
            for(StockTakeTaskDto stockTakeTaskDto : stockTakeTaskDtos){
                //如果有未完成的就累加1
                if(stockTakeTaskDto.getState().equals(1)){
                    check++;
                }
                //如果复盘完成同时差异数量不为0的话累加1
                if(!Objects.equals(nvl(stockTakeTaskDto.getDifferQuantity()), 0.0d)
                        && stockTakeTaskDto.getState().equals(2)
                        && (stockTakeTaskDto.getType().equals(21) ||stockTakeTaskDto.getType().equals(22))){
                    quantity++;
                }
            }
            StockTakeMaster stockTakeMaster = getById(stockTakeMasterId);
            if(check>0){
                //有未完成的任务设置状态为盘点中
                stockTakeMaster.setState(3);
            }else{
                //如果复盘后累加数量还是有差异状态改为盘点完成(需调整)
                if(quantity>0){
                    stockTakeMaster.setState(5);
                }
                //复盘后累加数量小于等于0说明数量无差异状态改为盘点完成(无差异)
                else{
                    stockTakeMaster.setState(4);
                }
            }
            updateById(stockTakeMaster);
        }
    }

    @Override
    public StockTakeMaster findBy(String field, String value) {
        QueryWrapper<StockTakeMaster> qw = new QueryWrapper<>();
        return getOne(qw.eq(field, value));
    }
}